package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"house/models"
	"strconv"
)

type HouseController struct {
	beego.Controller
}

func (c *HouseController) Add() {

	address := c.GetString("address")
	name := c.GetString("name")
	bhs := c.GetString("bh")
	bh, _ := strconv.Atoi(bhs)
	shs := c.GetString("sh")
	sh, _ := strconv.Atoi(shs)
	types := c.GetString("types")
	prices := c.GetString("price")
	price, _ := strconv.ParseFloat(prices, 64)
	ss := c.GetString("s")
	s, _ := strconv.ParseFloat(ss, 64)
	sums := c.GetString("sum")
	sum, _ := strconv.Atoi(sums)
	if address == "" || name == "" || bhs == "" || shs == "" || types == "" || prices == "" || ss == "" || sums == "" {
		res := models.JsonR{
			Code: 0,
			Msg:  "所有的信息都是必填项,请填写",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var house = models.House{
		Address: address,
		Name:    name,
		Bh:      bh,
		Sh:      sh,
		Types:   types,
		Price:   price,
		S:       s,
		Sum:     sum,
	}
	err := models.DB.Create(&house).Error
	if err != nil {
		res := models.JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := models.JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}

}

func (c *HouseController) List() {
	var houses []models.House
	err := models.DB.Where("deleted=false").Find(&houses).Error

	if err != nil {
		res := models.JsonR{
			Code: 0,
			Msg:  "展示房源失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := models.JsonR{
			Code: 200,
			Msg:  "展示房源成功",
			Data: houses,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *HouseController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Model(&models.House{}).Where("id=?", id).Update("deleted", true).Error
	if err != nil {
		res := models.JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := models.JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
